package config

import (
	"time"

	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

func InitMysql() *gorm.DB {
	logMode := logger.Info
	if viper.GetString("envirment.mode") != "dev" {
		logMode = logger.Error
	}
	db, err := gorm.Open(mysql.Open(viper.GetString("mysql.dsn")), &gorm.Config{
		Logger: logger.Default.LogMode(logMode),
	})
	if err != nil {
		panic(err)
	}
	sqlDB, _ := db.DB()
	sqlDB.SetMaxIdleConns(viper.GetInt("mysql.max-idle"))
	sqlDB.SetMaxOpenConns(viper.GetInt("mysql.max-open"))
	sqlDB.SetConnMaxLifetime(time.Hour)
	return db
}
